package com.minisoft.workhour.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.minisoft.workhour.model.ManhourRequest;

import java.util.Arrays;
import java.util.List;

/**
 * 工时API服务
 */
public class ManhourApiService {

    /**
     * API端点URL
     */
    private static final String API_URL = "https://itdev.huafagroup.com/project/api/project/team/Pxizacww/manhour/add";

    /**
     * Cookie信息
     */
    private static final String COOKIE = "language=zh; MSopened=cd21d7e48469c016d149bebbaf77e80d068b62ee; MSopened.cd21d7e48469c016d149bebbaf77e80d068b62ee=true; ajs_anonymous_id=430f46917e6947b8a3cbba407ed8b43d; _ga=GA1.1.1795855780.1745810623; _ga_QDXDSM4W55=GS2.1.s1752206313$o6$g0$t1752206313$j60$l0$h0; timezone=Asia/Shanghai; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22fengweilong-huafa-mgt-web%22%2C%22first_id%22%3A%221931a9e8c4115f3-026cb892a59c20e-26001051-921600-1931a9e8c4213f2%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTkzMWE5ZThjNDExNWYzLTAyNmNiODkyYTU5YzIwZS0yNjAwMTA1MS05MjE2MDAtMTkzMWE5ZThjNDIxM2YyIiwiJGlkZW50aXR5X2xvZ2luX2lkIjoiZmVuZ3dlaWxvbmctaHVhZmEtbWd0LXdlYiJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%22fengweilong-huafa-mgt-web%22%7D%2C%22%24device_id%22%3A%221931a9e8c4115f3-026cb892a59c20e-26001051-921600-1931a9e8c4213f2%22%7D; HUAFA-MARKET-PERMIT-API-TOKEN=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIwMDAwMTEzOTUiLCJuYmYiOjE3NTI1NjEwNzUsImV4cCI6MTc1MjU2ODI3NX0.vEv6iG4ZWE77eJ7SeyMCqsd3u0U5SOnSIpVDTtX4w6Q; SIAMTGT=TGT-45458384-qOx4GqjnSDspfRrXnS1OF9SeTU7TgkHIhSztFXhuumF7zQ9zpD-SIAM; ones-uid=MV8nFvTS; ones-lt=JhPW2B9xSWAtqvPgJpQiKN4LP0OKNX06fWTGF5SC7o0U2OgEzyNskR29zg2wBry2; ct=17feb403cab367f93cce8fd15491065e18564b3de04df77df37b6f045e0de5d5";

    /**
     * 发送单个工时记录
     *
     * @param manhourItem 工时项
     * @return 是否成功
     */
    public boolean submitSingleManhour(ManhourRequest.ManhourItem manhourItem) {
        if (manhourItem == null) {
            throw new IllegalArgumentException("工时项不能为空");
        }

        // 创建请求对象，包装成数组
        ManhourRequest request = new ManhourRequest(Arrays.asList(manhourItem));

        return submitManhourRequest(request);
    }

    /**
     * 批量发送工时记录
     *
     * @param manhourItems 工时项列表
     * @return 成功提交的数量
     */
    public int submitBatchManhours(List<ManhourRequest.ManhourItem> manhourItems) {
        if (manhourItems == null || manhourItems.isEmpty()) {
            throw new IllegalArgumentException("工时项列表不能为空");
        }

        int successCount = 0;

        for (int i = 0; i < manhourItems.size(); i++) {
            ManhourRequest.ManhourItem item = manhourItems.get(i);

            System.out.println("正在提交第 " + (i + 1) + "/" + manhourItems.size() +
                " 条工时记录: task=" + item.getTask() + ", description=" + item.getDescription());

            try {
                if (submitSingleManhour(item)) {
                    successCount++;
                    System.out.println("第 " + (i + 1) + " 条记录提交成功");
                } else {
                    System.err.println("第 " + (i + 1) + " 条记录提交失败");
                }

                // 添加延迟，避免请求过于频繁
                if (i < manhourItems.size() - 1) {
                    Thread.sleep(1000);
                }

            } catch (Exception e) {
                System.err.println("第 " + (i + 1) + " 条记录提交异常: " + e.getMessage());
                e.printStackTrace();
            }
        }

        System.out.println("批量提交完成，成功: " + successCount + "/" + manhourItems.size());
        return successCount;
    }

    /**
     * 发送工时请求
     *
     * @param request 工时请求
     * @return 是否成功
     */
    private boolean submitManhourRequest(ManhourRequest request) {
        try {
            String requestBody = JSON.toJSONString(request);
            System.out.println("请求体: " + requestBody);

            HttpResponse response = HttpRequest.post(API_URL)
                .header("Cookie", COOKIE)
                .header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .header("Content-Type", "application/json")
                .header("Accept", "*/*")
                .header("Host", "itdev.huafagroup.com")
                .header("Connection", "keep-alive")
                .body(requestBody)
                .timeout(30000)
                .execute();

            int statusCode = response.getStatus();
            String responseBody = response.body();

            System.out.println("API响应 - 状态码: " + statusCode + ", 响应体: " + responseBody);

            if (statusCode >= 200 && statusCode < 300) {
                System.out.println("工时提交成功");
                return true;
            } else {
                System.err.println("工时提交失败 - 状态码: " + statusCode + ", 响应: " + responseBody);
                return false;
            }

        } catch (Exception e) {
            System.err.println("发送工时请求异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}
